package cn.itsource.exam.service.impl;

import cn.itsource.exam.domain.*;
import cn.itsource.exam.dtos.indto.UpdatePwdInDTO;
import cn.itsource.exam.enums.LogOperateTypeEnum;
import cn.itsource.exam.enums.UserTypeEnum;
import cn.itsource.exam.mapper.ClassInfoMapper;
import cn.itsource.exam.mapper.LoginMapper;
import cn.itsource.exam.mapper.StudentInfoMapper;
import cn.itsource.exam.query.UserInfoQuery;
import cn.itsource.exam.service.LogInfoService;
import cn.itsource.exam.service.StudentInfoService;
import cn.itsource.exam.util.Md5Helper;
import cn.itsource.exam.util.PageList;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by su on 2020/7/8.
 */
@Service
public class StudentInfoServiceImpl implements StudentInfoService {

    @Autowired
    private StudentInfoMapper userInfoMapper;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Autowired
    private LogInfoService logInfoService;

    @Autowired
    private RoleServiceImpl roleService;

    /**
     * 增加或修改用户
     * @param user
     * @return
     */
    @Override
    public String modifyUser(StudentInfo user,String operateuser) {
        try{
            int count = 0;
            Map<String,Object> map = new HashMap<>();
            if(StringUtils.isNotEmpty(user.getPhone())){
                map.put("phone",user.getPhone());
            }
            if(StringUtils.isNotEmpty(user.getIdnumber())){
                map.put("idnumber",user.getIdnumber());
            }
            List<StudentInfo> list = userInfoMapper.selectByMap(map);
            if(user.getId() != null){   // 如果ID不为空说明是修改
                if(list != null && list.size() > 0){
                    for(StudentInfo userInfo:list){
                        if(!userInfo.getId().equals(user.getId()) && userInfo.getPhone().equals(user.getPhone())){
                            return "该电话已存在!";
                        }
                        if(!userInfo.getId().equals(user.getId()) && userInfo.getIdnumber().equals(user.getIdnumber())){
                            return "该身份证号已存在!";
                        }
                    }
                }
                user.setModifytime(new Date());
                count = userInfoMapper.updateById(user);
                if(count > 0){
                    logInfoService.addLogInfo(new LogInfo(LogOperateTypeEnum.STUDENT.getId(),"修改"+user.getName()+"信息",operateuser));
                }
            }else{
                if(list != null && list.size() > 0){
                    for(StudentInfo userInfo:list){
                        if(userInfo.getPhone().equals(user.getPhone())){
                            return "该电话已存在!";
                        }
                        if(userInfo.getIdnumber().equals(user.getIdnumber())){
                            return "该身份证号已存在!";
                        }
                    }
                }

                user.setAddtime(new Date());
                user.setStatus(0);

                // 往login表赋值
                Login login = operateLogin(user);
                //主表给次表赋值id
                user.setId(login.getId());
                /******login表操作结束*****/
                count = userInfoMapper.insert(user);
                roleService.addUserRole(user.getId(),LogOperateTypeEnum.STUDENT.getId()+"");
                if(count > 0){
                    logInfoService.addLogInfo(new LogInfo(LogOperateTypeEnum.STUDENT.getId(),"新增"+user.getName()+"信息",operateuser));
                }
            }
            return count > 0 ? "":"操作失败";
        }catch (Exception e){
            e.printStackTrace();
            return "程序错误";
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    public String delUser(Long id,String operateuser) {
        StudentInfo user = userInfoMapper.selectById(id);
        if(user == null || user.getStatus() != 0){
            return "用户不存在!";
        }
        user.setStatus(1);
        user.setModifytime(new Date());
        int count = userInfoMapper.updateById(user);
        if(count > 0){
            logInfoService.addLogInfo(new LogInfo(LogOperateTypeEnum.STUDENT.getId(),"删除"+user.getName()+"信息",operateuser));
        }
        return count > 0 ? "":"操作失败";
    }

    /**
     * 根据主键查询用户
     * @param id
     * @return
     */
    @Override
    public StudentInfo getUserById(Long id) {
        StudentInfo userInfo = userInfoMapper.selectById(id);
        if(userInfo != null && userInfo.getStatus() == 0){
            return userInfo;
        }
        return null;
    }

    /**
     * 分页查询用户
     * @param paramIn
     * @return
     */
    @Override
    public PageList<StudentInfo> getUserList(UserInfoQuery paramIn) {
        Integer count = userInfoMapper.countUserList(paramIn);
        if (count == null || count == 0){
            return  new PageList<StudentInfo>();
        }
        PageList<StudentInfo> list =  new PageList<StudentInfo>(count,userInfoMapper.selectUserList(paramIn));
        return list;
    }

    @Override
    public String batchDelUser(String ids,String operateuser) {
        if(StringUtils.isEmpty(ids)){
            return "请选择要删除的数据!";
        }
        List<StudentInfo> list = userInfoMapper.selectBatchIds(Arrays.asList(ids.split(",")));
        int count = userInfoMapper.batchdel(Arrays.asList(ids.split(",")));
        if(count > 0){
            new Thread(){   // 异步插入日志
                public void run(){
                    for(StudentInfo user:list){
                        logInfoService.addLogInfo(new LogInfo(LogOperateTypeEnum.STUDENT.getId(),"删除"+user.getName()+"信息",operateuser));
                    }
                }
            }.start();
        }
        return count > 0 ? "":"操作失败";
    }

    /**
     * 上传学生信息
     * @param file
     * @param request
     * @return
     */
    @Override
    public String uploadUser(MultipartFile file, HttpServletRequest request) {
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = wb.getSheetAt(0); //根据页面index 获取sheet页
            List<StudentInfo> importDatas = getUserByFile(sheet);
            if(importDatas == null || importDatas.size() == 0){
                return "没有需要导入的数据,请检查!";
            }
            //存入数据库
            String phones = "";
            for (StudentInfo imdata : importDatas) {
                if(imdata.getPhone().indexOf(phones) > 0){
                    return "电话不能重复,请检查!";
                }
                phones += imdata.getPhone()+",";
            }
            List<String> ps = Arrays.asList(phones.split(","));
            List<StudentInfo> list = userInfoMapper.selectByPhones(ps);

            if(list != null && list.size() > 0){
                String p = Joiner.on(",").join(list.stream().map(StudentInfo::getPhone).collect(Collectors.toList()));
                return p+"电话已存在,请检查!";
            }
            StudentInfo info = (StudentInfo)request.getSession().getAttribute(request.getHeader("U-TOKEN"));
            for (StudentInfo user : importDatas) {
                user.setStatus(0);
                user.setModifytime(new Date());
               int count = userInfoMapper.insert(user);
                if(count > 0){
                    roleService.addUserRole(user.getId(),LogOperateTypeEnum.STUDENT.getId()+"");
                    logInfoService.addLogInfo(new LogInfo(LogOperateTypeEnum.STUDENT.getId(),"新增"+user.getName()+"信息",info.getName()));
                }
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "导入失败!";
    }

    /**
     * 解析excel文件
     * @param sheet
     * @return
     */
    private List<StudentInfo> getUserByFile(XSSFSheet sheet){
        //实体类集合
        List<StudentInfo> importDatas = new ArrayList<>();
        XSSFRow row = null;
        //循环sesheet页中数据从第二行开始，第一行是标题
        Map<String,Object> map = new HashMap<>();
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            //获取每一行数据
            row = sheet.getRow(i);
            StudentInfo data = new StudentInfo();
            // 获取班级
            String classname = getCellValue(row,1);
            List<ClassInfo> list = classInfoMapper.selectByCondition(classname);
            if(list != null && list.size() > 0){
                data.setClassId(list.get(0).getId());
                data.setClassname(list.get(0).getClassname());
                data.setClassNum(list.get(0).getClassnum());
            }else{
                data.setClassname(row.getCell(1).getStringCellValue());
            }
            // 姓名
            data.setName(getCellValue(row,2));
            // 年龄
            String age = getCellValue(row, 3);
            data.setAge(StringUtils.isNotBlank(age) ? Integer.parseInt(age) : null);
            // 性别
            String sex = getCellValue(row,4);
            data.setSex(StringUtils.isBlank(sex) ? null : "女".equals(sex) ? 1 : "男".equals(sex) ? 0 : -1);
            // 居住地址
            data.setAddress(getCellValue(row,5));
            //身份证号码、
            data.setIdnumber(getCellValue(row, 6));
            // 紧急联系人
            data.setEmergencycontact(getCellValue(row, 7));
            // 电话
            data.setPhone(getCellValue(row,8));
            // qq
            data.setQq(getCellValue(row, 9));
            // 微信
            data.setWechat(getCellValue(row, 10));
            // 学历
            data.setEducation(getCellValue(row, 11));
            // 专业
            data.setMajor(getCellValue(row, 12));
            // 毕业院校
            data.setGraduated(getCellValue(row, 13));
            // 毕业时间
            data.setGraduationtime(getCellValue(row, 14));
            // 报名情况
            data.setRegistration(getCellValue(row, 15));
            // 备注
            data.setRemark(getCellValue(row, 16));
            // 营销人
            data.setMarketername(getCellValue(row, 17));
            // 协助人员
            data.setHelpersname(getCellValue(row, 18));
            data.setAddtime(new Date());
            importDatas.add(data);
        }
        return importDatas;
    }

    private String getCellValue(XSSFRow row,int cell){
        if(row.getCell(cell) != null){
            row.getCell(cell).setCellType(CellType.STRING);
            return row.getCell(cell).getStringCellValue();
        }
        return "";
    }

    private Login operateLogin(StudentInfo user){
        Login login = new Login();
        login.setPassword(Md5Helper.MD5("123456"));
        login.setPhone(user.getPhone());
        login.setName(user.getName());
        login.setStatus("0");
        login.setU_type(UserTypeEnum.STUDENT.getId());

        loginMapper.insert(login);
        return login;
    }
}
